import API from "@/api";
import type { ILessonResult } from "@/pages/lowPricedCourse/trialCourseHome/courseList/index.vue";

export interface IImitationRequest {
  scoreLimit: number;
  oralImitation: IOralImitation[];
}

export interface IOralImitation {
  img: string;
  number: number;
  oral_id: string;
  sentences: string;
  uk_voice: string;
  us_voice: string;
  score: number;
  user_voice: string;
}

export interface IOralImitationLesson {
  isRelearn: boolean;
  isNeedLaunchPage: boolean;
  data: {
    questions: IOralImitation[],
    stepLength: number;
    currentQuestionIndex: number;
    scoreLimit: number;
  }
}

export const requestImitationData = (sectionId: number): Promise<ILessonResult> => {
  return new Promise((resolve, reject) => {
    API.oralImitation({ section_id: sectionId }).then(res => {
      let result = res as IImitationRequest;

      let isRelearn = false;
      let isNeedLaunchPage = false;
      let currentQuestionIndex = 0;

      const firstItem = result.oralImitation[0];
      const lastItem = result.oralImitation[result.oralImitation.length - 1];

      if (!(firstItem.score >= 60 || firstItem.number >= 2 || firstItem.user_voice)) {
        isNeedLaunchPage = true;
      }

      if (lastItem?.number >= 2 || lastItem?.score >= 60) {
        isRelearn = true;
        currentQuestionIndex = 0;
      } else {
        for (let i = 0, len = result.oralImitation.length; i < len; i++) {
          const el = result.oralImitation[i];
          if (!(el.score >= 60 || el.number >= 2)) {
            isRelearn = false;
            currentQuestionIndex = i;
            break;
          }
        }
      }

      let data: IOralImitationLesson = {
        isRelearn,
        isNeedLaunchPage: isRelearn || isNeedLaunchPage,
        data: {
          currentQuestionIndex,
          scoreLimit: result.scoreLimit,
          questions: result.oralImitation,
          stepLength: 100 / result.oralImitation.length,
        }
      }

      resolve(data);
    })
      .catch(() => {
        reject();
      })
  })
}